﻿using Microsoft.Extensions.Logging;
using Ops.Exchange.Forwarder;
using Ops.Exchange.Model;
using Ops.Host.Core.Management;
using Ops.Host.Core.Models;
using Ops.Host.Core.Utils;

namespace Ops.Host.Core.Services;

internal sealed class AlarmService : IAlarmService
{
    private readonly IFreeSql _freeSql;
    private readonly ILogger _logger;

    public AlarmService(IFreeSql freeSql, ILogger<AlarmService> logger) 
    { 
        _freeSql = freeSql;
        _logger = logger;
    }

    public async Task<ReplyResult> SaveAlarmsAsync(ForwardData data)
    {
        if (data.Values.Length == 0)
        {
            return ReplyResultHelper.Ok();
        }

        var alarmDicts = await _freeSql.Select<DictInfo>().Where(s => s.Category == DictManager.Alarm).ToListAsync();
        if (alarmDicts.Count == 0)
        {
            return ReplyResultHelper.Ok();
        }

        var alarmValues = data.Values[0].GetBitArray(); // 警报数据
        var alarmRecords = new List<AlarmRecord>();
        try
        {
            // 字典配置基数从 1 开始。
            for (int i = 0; i < alarmValues!.Length; i++)
            {
                if (alarmValues[i])
                {
                    var alarmDict = alarmDicts.FirstOrDefault(s => s.Code == (i + 1).ToString());
                    if (alarmDict != null)
                    {
                        var alarm = new AlarmRecord
                        {
                            Station = data.Schema.Station,
                            Classify = alarmDict.Name,
                            Desc = alarmDict.Alias,
                            CreatedAt = DateTime.Now,
                        };
                        alarmRecords.Add(alarm);

                        // 推送消息
                        await MessageTaskQueueManager.Default.QueueAsync(new Message(alarm.Station, MessageClassify.Alarm, alarm.Desc ?? ""));
                    }
                }
            }

            _freeSql.Insert(alarmRecords).ExecuteAffrows();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"[AlarmService] Error Tag：{data.Tag}");
            return ReplyResultHelper.Error();
        }

        return ReplyResultHelper.Ok();
    }
}
